import * as React from 'react'
import { InputItem, Toast, Modal } from 'antd-mobile'
import { NavBar, Item, Button, PayInput } from 'components'
import { formatPriceStr } from '../../methods'
import './SaleBeans.less'
import { post } from '../../../../utils'

export default class SaleBeans extends React.Component<any, any> {

    public state = {
        hdNumber: '', // 恒豆数量,
        visible: false,
        discount: '',
        showPayInput: false,
    }
    public render(): JSX.Element {
        const { hdNumber, discount, visible, showPayInput } = this.state
        const { userInfo } = this.props
        return (
            <div className="saleBeans">
                <NavBar
                    title="发布恒豆出售信息"
                    fixed={true}
                    right={<span className="saleBeans_soldNotice" onClick={() => {this.setState({visible: true})}}>出售规则</span>}
                />
                <div className="saleBeans_transferInfo">
                    <Item 
                        className="saleBeans_transferInfo_item" 
                        title={<div className="saleBeans_transferInfo_title">转让折扣</div>}
                        value={<div className="saleBeans_transferInfo_value"><input maxLength={3} value={discount} onChange={this.handleDiscount} type="tel" placeholder="转让折扣(0~10之间)"/></div>}
                    />
                </div>
                <div className="saleBeans_content">
                    <div className="saleBeans_content_title">出售恒豆数量</div>
                    <div className="saleBeans_content_inputWrap">
                        <div>￥</div>
                        <div>
                            <InputItem
                                type="number"
                                value={hdNumber}
                                defaultValue={hdNumber}
                                className="saleBeans_content_inputWrap_input"
                                maxLength={5}
                                clear={(hdNumber.length > 0) ? true : false}
                                onChange={this.handleInputChange}
                                placeholder="恒豆数量最低限额500"
                            />
                        </div>
                        {
                            (hdNumber.length > 0) 
                            ? <div/>
                            : <div onClick={this.handleInputAll}>全部</div>
                        }
                    </div>
                    <div className="saleBeans_content_balance">可用恒豆数量: {userInfo && formatPriceStr(userInfo.bean)}</div>
                </div>
                <div className="saleBeans_operation">
                    <Button className="saleBeans_operation_btn" onClick={this.handleSaleBeans} disabled={(discount.length > 0 && hdNumber.length > 0) ? false : true}>确定发布</Button>
                </div>
                <Modal
                    visible={visible}
                    transparent={true}
                    maskClosable={false}
                    // onClose={this.onClose('modal1')}
                    title="恒豆出售规则"
                    footer={[{
                        text: '我知道了',
                        onPress: () => { this.setState({ visible: false }) },
                        style: {
                            height: '2.5rem',
                            fontSize: '0.8rem',
                            color: '#fa0000'
                        }
                    }]}
                >
                    <div className="beans_order_modal">
                        <div>
                            <div className="title">出售条件</div>
                            <div className="label">1.订单金额大于20元(含);</div>
                            <div className="label">2.恒豆数量大于1000个(含);</div>
                            <div className="label">3.恒豆支付不得超过每笔订单应付金额的50%;</div>
                        </div>
                        <div>
                            <div className="title">出售折扣</div>
                            <div className="label">1.折扣小数位只保留一位</div>
                            <div className="label">2.折扣范围为<span style={{color: '#fa0000'}}>0~10</span>，折扣值应该大于0，小于等于10</div>
                        </div>
                        <div>
                            <div className="title">出售数量</div>
                            <div className="label">1.使用恒豆数量为1000的整数倍;</div>
                            <div className="label">2.1000恒豆抵10元;</div>
                        </div>
                    </div>
                </Modal>
                <Modal
                    visible={showPayInput}
                    popup={true}
                    animationType="slide-up"
                    onClose={() => {this.setState({showPayInput: false})}}
                >
                    <div className="saleBeans_content_payPswVerify">
                        <PayInput autoFoucs={true} pwdHide={false} onComplete={(val: string) => { this.handleVerifyPayPsw(val) }} />       
                    </div>                 
                </Modal>
            </div>
        )
    }

    private handleSaleBeans = () => {
        const { userInfo } = this.props
        const { hdNumber, discount } = this.state
        if (isNaN(parseFloat(discount)) || discount.indexOf('.') === 0 || (discount.indexOf('0') === 0 && discount.indexOf('.') !== 1) || discount.indexOf('.') === 2) {
            Toast.info('折扣值格式不正确，请参阅出售规则')
            return
        }
        if (parseInt(hdNumber, 10) < 500 || parseInt(hdNumber, 10) > parseInt(userInfo.bean, 10) || parseInt(hdNumber, 10) % 10 !== 0) {
            Toast.info('输入恒豆的数量不正确，请参阅出售规则')
            return
        }
        if (!userInfo.pay_pwd) {
            Toast.info('请先设置支付密码', 2, () => {this.props.history.push('/My/authenticationNewPass/1')})
            return
        }
        this.setState({
            showPayInput: true
        })
    }
    private handleVerifyPayPsw = (val: string) => {
        Toast.info('验证中...', 0)
        const { userInfo } = this.props
        post('usersapi/userPayPwdGet', {
            userId: userInfo.id,
            paypwd: val
        }).then((data: any) => {
            if (data.code === 0) {
                Toast.fail('密码错误')
            }
            if (data.code === 2) {
                Toast.hide()
                this.handleSubmitOrder()                
            }
            return
        }).catch(() => {
            Toast.hide()
        })
    }
    private handleSubmitOrder = () => {
        const { userInfo, SET_USER_INFO } = this.props
        const { hdNumber, discount } = this.state
        Toast.info('发布中...')
        post('beanapi/beanRelease', {
            userId: userInfo.id,
            amount: parseInt(hdNumber, 10),
            discount: parseFloat(discount),
            discount_info: ''
        }).then((data: any) => {
            let obj = Object.assign({}, userInfo)
            obj.bean = (parseInt(userInfo.bean, 10) - parseInt(hdNumber, 10)).toString()
            SET_USER_INFO(obj)
            this.setState({
                showPayInput: false
            })
            Toast.info('发布成功！', 2, () => {this.props.history.goBack()})
        })
    }
    private handleDiscount = (e: any) => {
        let val = e.target.value.replace(/[^\d{1,}\.\d{1,}|\d{1,}]/g, '')
        if (parseInt(val, 10) > 10 || parseInt(val, 10) < 0) {
            Toast.info('折扣值超出范围！', 1.5, () => {this.setState({discount: ''})})
            return
        }
        this.setState({
            discount: val
        })
    }

    private handleInputChange = (value: string) => {
        const { userInfo } = this.props
        let val = value
        if (value && (parseInt(value, 10) > parseInt(userInfo.bean, 10))) {
            val = userInfo.bean
        }
        this.setState({
            hdNumber: val
        })
    }
    private handleInputAll = () => {
        const { userInfo } = this.props
        this.setState({
            hdNumber: userInfo.bean
        })
    }
}